#include "threadPool.h"

typedef struct train_s{
    int type;//代表本次传输的命令的种类，长度4B
    int lenth;//代表小火车正文的长度，长度4B
    char value[1024];//代表要传输的命令正文
}train_t;

int authPasswd(int netfd) {
    char username[256];
    char password[256];
    train_t auth_train;
    char response[1024];

    bzero(&auth_train, sizeof(auth_train));
    int ret = recv(netfd, &auth_train, sizeof(auth_train.type) + sizeof(auth_train.lenth), MSG_WAITALL);
    if (ret <= 0) return -1;
    ret = recv(netfd, auth_train.value, auth_train.lenth, MSG_WAITALL);
    if (ret <= 0) return -1;
    auth_train.value[auth_train.lenth] = '\0';
    strncpy(username, auth_train.value, sizeof(username) - 1);
    username[sizeof(username) - 1] = '\0';


    bzero(&auth_train, sizeof(auth_train));
    ret = recv(netfd, &auth_train, sizeof(auth_train.type) + sizeof(auth_train.lenth), MSG_WAITALL);
    if (ret <= 0) return -1;
    ret = recv(netfd, auth_train.value, auth_train.lenth, MSG_WAITALL);
    if (ret <= 0) return -1;
    auth_train.value[auth_train.lenth] = '\0';
    strncpy(password, auth_train.value, sizeof(password) - 1);
    password[sizeof(password) - 1] = '\0';


    struct spwd *sp = getspnam(username); //从shadow文件获取用户名对应的密文
    if (sp == NULL) {
        strcpy(response, "user not found");
        send(netfd, response, strlen(response), MSG_NOSIGNAL);
        return -1;
    }

    char *storedPasswd = sp->sp_pwdp;
	
	//printf("提取的密文：%s\n",storedPasswd);
	
    char *saltEnd = strrchr(storedPasswd, '$'); // Find last '$'
    if (saltEnd == NULL) {
        strcpy(response, "Invalid password format");
        send(netfd, response, strlen(response), MSG_NOSIGNAL);
        return -1;
    }
    size_t saltLen = saltEnd - storedPasswd + 1;
    char salt[128];
    strncpy(salt, storedPasswd, saltLen);
    salt[saltLen] = '\0';
	
	//printf("salt值：%s\n",salt);
	
    char *encrypted = crypt(password, salt);
    if (encrypted == NULL) {
        strcpy(response, "Encryption error");
        send(netfd, response, strlen(response), MSG_NOSIGNAL);
        return -1;
    }
    
    //printf("encrypted = %s\n",encrypted);
    
    if (strcmp(encrypted, storedPasswd) == 0) {
        strcpy(response, "AUTH_SUCCESS");
        send(netfd, response, strlen(response), MSG_NOSIGNAL);    
        return 0;
    } else {
        strcpy(response, "密码错误！");
        send(netfd, response, strlen(response), MSG_NOSIGNAL);
        return -1;
    }
}
